<?php
namespace app\admin\controller;

use think\Db;
use think\Cache;
use app\admin\controller\Admin;

class Clean extends Admin
{
    public function index()
    {
        $data = array(
            [
                'title' => '缩略图更新',
                'url' => url('admin/clean/thumb'),
            ]
        );

        $this->assign('data', $data);
        return $this->fetch('admin/clean/index');
    }

    /**
     * 清理缩略图文件
     *
     * @return json
     */
    public function thumb()
    {
        $thumbPath = ROOT_PATH . 'upload' . DS . 'thumb';

        // 判断文件夹是否可写
        if (!is_writable($thumbPath)) {
             return $this->response(777);
        }
        
        // 清理文件操作
        $delete = $this->deleteFile($thumbPath);

        return $this->response($delete ? 200 : 201);
    }

    /** 
     * 删除目录下所有文件
     *
     * @return bool
     */
    function deleteFile($path) {
        $op = dir($path);
        while (false != ($item = $op->read())) {
            if($item == '.' || $item == '..') {
                continue;
            }
            if (is_dir($op->path . DS . $item)) {
                deleteFile($op->path . DS . $item);
                rmdir($op->path . DS . $item);
            } else {
                unlink($op->path. DS . $item);
            }
        }

        return true;
    }
}
